/**
 * @author EasonChan
 *
 * Nov 17, 2010
 */
package com.musicgeek.dao.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

public class ConnectionPool {
	private static LinkedList<Connection> pool;
	private static final int POOL_MAX_SIZE = 5;
	private static final int POOL_INIT_SIZE = 2;
	private static String url = "jdbc:mysql://localhost:3306/musicgeek?user=root&password=q1";

	// Init Connection pool
	static {
		pool = new LinkedList<Connection>();
		for (int i = 0; i < POOL_INIT_SIZE; i++) {
			pool.add(createConnection());
		}
	}

	// Get Connection
	public static synchronized Connection getConnection() {
		if (pool == null)
			pool = new LinkedList<Connection>();
		Connection conn;
		if (pool.isEmpty()) {
			conn = createConnection();
		} else {
			conn = pool.removeLast();
		}
		return conn;
	}

	// Close the conn if pool is full otherwise add the conn back to the pool
	public static synchronized void releaseConnection(Connection conn) {
		if (pool.size() > POOL_MAX_SIZE) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			pool.add(conn);
		}
	}

	private static Connection createConnection() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

}
